#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :添加文件后缀.py
# @Time      :2024/5/27 
# @Author    :CL
# @email     :1037654919@qq.com

import os


# 定义一个字典来映射文件类型和对应的后缀名
type_to_extension = {
    'image/jpeg': '.jpg',
    'image/png': '.png',
    'application/pdf': '.pdf',
    # 添加更多文件类型和对应的后缀名
}
def add_extension_to_file(file_path):
    # 使用os模块获取文件的MIME类型
    mime_type = 'unknown'  # 默认为unknown
    with open(file_path, 'rb') as f:
        # 根据文件头部信息判断文件类型
        data = f.read(32)
        print(file_path,data)
        if data.startswith(b'\xff\xd8'):
            mime_type = 'image/jpeg'
        elif data.startswith(b'\x89PNG\r\n\x1a\n'):
            mime_type = 'image/png'
        elif data.startswith(b'%PDF-'):
            mime_type = 'application/pdf'

    # 根据MIME类型获取文件后缀名
    new_extension = type_to_extension.get(mime_type, '.unknown')

    # 为文件添加正确的后缀
    name, _ = os.path.splitext(file_path)
    new_file_name = file_path + new_extension
    new_file_path = os.path.join(os.path.dirname(file_path), new_file_name)
    os.rename(file_path, new_file_path)
    print(f"文件 {file_path} 已重命名为 {new_file_name}")
# 定义有效后缀
valid_extensions = ['.jpg', '.png', '.gif', '.txt', '.pdf', '.csv']

def has_extension(filename):
    # 获取文件的后缀
    _, ext = os.path.splitext(filename)
    # 判断文件名是否以后缀结尾
    return  ext in valid_extensions
def process_folder(input_path):
    for root, dirs, files in os.walk(input_path):
        for file_name in files:
            file_path = os.path.join(root, file_name)
            # print(f"处理文件 {file_path}")
            # 如果文件名有后缀名，则跳过
            if has_extension(file_path):
                continue
            print(f"处理文件 {file_path}")
            add_extension_to_file(file_path)

# 指定要遍历的文件夹路径
input_path = r'/media/chenglei3/77D014CED257D1411/images/bing_pic/'

# 执行遍历并处理文件
process_folder(input_path)